const DiscountCoupon = require("../models/discountCouponModel");


exports.createDiscountCoupon = async (req, res) => {
  try {
    const {
      occasionName,
      couponCode,
      expiryDate,
      value,
      couponType,
      description,
      status,
    } = req.body;

    
    if (!occasionName || !couponCode || !expiryDate || !value) {
      return res.status(400).json({ message: "Missing required fields!" });
    }

    
    const newCoupon = new DiscountCoupon({
      occasionName,
      couponCode,
      expiryDate,
      value,
      couponType: couponType || "value",
      description: description || "",
      status: status || "Active",
    });

    await newCoupon.save();
    res.status(201).json({ message: "Discount coupon created!", coupon: newCoupon });
  } catch (error) {
    console.error(error);
    if (error.code === 11000) {
      return res.status(400).json({ message: "Coupon code must be unique!" });
    }
    res.status(500).json({ message: "Internal server error" });
  }
};

// READ ALL
exports.getAllDiscountCoupons = async (req, res) => {
  try {
    const coupons = await DiscountCoupon.find();
    res.status(200).json(coupons);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Internal server error" });
  }
};

// READ ONE
exports.getDiscountCouponById = async (req, res) => {
  try {
    const coupon = await DiscountCoupon.findById(req.params.id);
    if (!coupon) {
      return res.status(404).json({ message: "Coupon not found!" });
    }
    res.status(200).json(coupon);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Internal server error" });
  }
};

// UPDATE
exports.updateDiscountCoupon = async (req, res) => {
  try {
    const { id } = req.params;
    const updated = await DiscountCoupon.findByIdAndUpdate(id, req.body, { new: true });
    if (!updated) {
      return res.status(404).json({ message: "Coupon not found!" });
    }
    res.status(200).json({ message: "Coupon updated!", coupon: updated });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Internal server error" });
  }
};

// DELETE
exports.deleteDiscountCoupon = async (req, res) => {
  try {
    const { id } = req.params;
    const coupon = await DiscountCoupon.findByIdAndDelete(id);
    if (!coupon) {
      return res.status(404).json({ message: "Coupon not found!" });
    }
    res.status(200).json({ message: "Coupon deleted successfully!" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Internal server error" });
  }
};